﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using WebMatrix.WebData;

using iKnow.Models;
using System.Text.RegularExpressions;

namespace iKnow.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(String id, int version = 0)
        {
            ViewBag.IsAuthenticated = false;

            if (WebSecurity.IsAuthenticated)
                ViewBag.IsAuthenticated = true;

            iKnowEntities entities
                = new iKnowEntities();

            var articles = from a in entities.Article
                           where a.Title.ToLower().Equals(id.ToLower())
                           select a;

            if (articles.Count() < 1)
                return RedirectToAction("Create", new { id = id });

            ViewBag.Versions = articles.Select(a => a.Version).ToList();
            int currentVersion = articles.Max(a => a.Version);

            if (version == 0)
                version = currentVersion;

            var article = entities.Article.Where(a => a.Version.Equals(version) && a.Title.ToLower().Equals(id.ToLower()));

            if (article.Count() < 1)
                return RedirectToAction("Index", new { id = "Start" });

            return View(article.First());
        }

        public ActionResult Create(String id)
        {
            if (!WebSecurity.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");

            Article article
                = new Article()
                {
                    Title = id
                };

            return View(article);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Article model)
        {
            if (!WebSecurity.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");

            model.Version = 1;
            model.Changed = DateTime.Now;
            model.ChangedBy = @WebSecurity.CurrentUserName;

            if (ModelState.IsValid)
            {
                iKnowEntities entities
                    = new iKnowEntities();

                // look for links
                Regex regex = new Regex(@"\[\[[^\[\]]*\]\]");
                model.Text
                    = regex.Replace(model.Text, delegate(Match match)
                    {
                        string m = match.ToString();
                        m = m.Replace("[[", "");
                        m = m.Replace("]]", "");
                        return "<a href=\"" + @Url.Content("~/Article") + "/" + m + "\">" + m + "</a>";
                    });

                entities.Article.AddObject(model);
                entities.SaveChanges();

                return RedirectToAction("Index", new { title = model.Title });
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult Edit(String id, int version = 0)
        {
            if (!WebSecurity.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");

            iKnowEntities entities
                = new iKnowEntities();

            var articles = from a in entities.Article
                           where a.Title.ToLower().Equals(id.ToLower())
                           select a;

            if (articles.Count() < 1)
                return RedirectToAction("Create", new { id = id });

            ViewBag.Versions = articles.Select(a => a.Version).ToList();
            int currentVersion = articles.Max(a => a.Version);

            if (version == 0)
                version = currentVersion;

            var article = entities.Article.Where(a => a.Version.Equals(version) && a.Title.ToLower().Equals(id.ToLower()));

            if (article.Count() != 1)
                return RedirectToAction("Index", new { id = id });

            return View(article.Single());
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Article model)
        {
            if (!WebSecurity.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");

            if (ModelState.IsValid)
            {
                iKnowEntities entities
                    = new iKnowEntities();


                var articles = from a in entities.Article
                               where a.Title.Equals(model.Title)
                               select a;

                int currentVersion = articles.Max(a => a.Version);

                Article ar = (from a in articles
                              where a.Version.Equals(currentVersion)
                              select a).Single();

                // look for links
                Regex regex = new Regex(@"\[\[[^\[\]]*\]\]");
                model.Text
                    = regex.Replace(model.Text, delegate(Match match)
                    {
                        string m = match.ToString();
                        m = m.Replace("[[", "");
                        m = m.Replace("]]", "");
                        return "<a href=\"" + @Url.Content("~/Article") + "/" + m + "\">" + m + "</a>";
                    });

                Article newArticle = new Article()
                {
                    Text = model.Text,
                    Changed = DateTime.Now,
                    ChangedBy = @WebSecurity.CurrentUserName,
                    Title = ar.Title,
                    Version = ar.Version + 1
                };

                entities.Article.AddObject(newArticle);

                entities.SaveChanges();

                return RedirectToAction("Index", new { title = model.Title });
            }
            else
            {
                return View(model);
            }
        }
    }
}
